from django.shortcuts import render

# Create your views here.
# 完成注册业务逻辑的功能实现
from rest_framework.response import Response
from rest_framework.views import APIView
from random import randint
from django_redis import get_redis_connection
from celery_tasks.sms.tasks import send_sms_code
# 导入第三方容联-云通讯短信包
from go_shopping.libs.yuntongxun.sms import CCP


# 完成短信验证码的功能
class SMSCodeView(APIView):
    def get(self, request, mobile):
        # 判断短信验证码过期
        conn = get_redis_connection('verify')  # 链接缓存数据库
        flag = conn.get('sms_flag_%s' % mobile)
        if flag:
            return Response({'message': '请求过于频繁'}, status=400)

        # 1.生成短信验证码(字符串)
        sms_code = '%06d' % randint(0, 999999)
        print(sms_code)

        # 2.保存短信验证码(减少redis数据库的频繁操作可以生成一个管道对象)
        # 生成管道对象
        pl = conn.pipeline()
        pl.setex('sms_%s' % mobile, 300, sms_code)  # 将验证码写入缓存数据库中
        # 设置短信时间依据
        pl.setex('sms_flag_%s' % mobile, 60, 1)
        pl.execute()  # 添加命令到redis中并执行

        # 3.发送短信验证玛
        # ccp = CCP()
        # ccp.send_template_sms(mobile, [sms_code, '5'], 1)  # 手机号-（短信验证码，时间）-模板
        # 调用celery异步任务的方法
        send_sms_code.delay(mobile,sms_code)

        # 4.返回结果
        return Response({'message': 'ok'})

